package com.financial.service.yspay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.financial.service.yspay.connector.SysconfigFeign;
import com.financial.service.yspay.dto.FinancialYsPayDTO;
import com.financial.service.yspay.mq.FinancialYsPayReturnMQConfig;
import com.financial.service.yspay.service.FinancialYsCallBackService;
import com.financial.service.yspay.service.FinancialYsPayVerifyJsonSignService;
import com.financial.service.yspay.utils.JsonUtils;
import com.financial.service.yspay.utils.ParamUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @Author WANGNING
 * @Email wyn20140226@aliyun.com
 * @Description //TODO
 * @Date 2019/11/13 16:41
 */
@Service
public class FinancialYsCallBackServiceImpl implements FinancialYsCallBackService {
    private static Logger logger = LoggerFactory.getLogger(FinancialYsCallBackServiceImpl.class);
    @Autowired
    private Producer producer;

    @Autowired
    private FinancialYsPayVerifyJsonSignService financialYsPayVerifyJsonSignService;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    /**
     * 银盛微信支付异步回调地址
     *
     * @param params
     * @param response
     */
    @Override
    public void weChatCallBack(Map<String, String> params, HttpServletResponse response) {
        PrintWriter printWriter = null;
        String ysPayWechatJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsPayDTO = JsonUtils.parseObject(ysPayWechatJson);
        logger.info("FinancialYsCallBackServiceImpl.weChatCallBack()---请求到的银盛微信支付异步回执信息为：" + params);
        try {
            printWriter = response.getWriter();
            boolean flag = financialYsPayVerifyJsonSignService.verifySign(params, financialYsPayDTO);
            logger.info("银盛微信支付异步回执签名验证情况" + flag);
            if (flag == true) {
                String msg = JSON.toJSONString(params, SerializerFeature.DisableCircularReferenceDetect);
                Message message = new Message(FinancialYsPayReturnMQConfig.YS_TOPIC, FinancialYsPayReturnMQConfig.YS_SERVICE_WECHATPAY_TAG, msg.getBytes());
                producer.send(message);
                //TODO 备注
                logger.info("FinancialYsCallBackServiceImpl.weChatCallBack()---银盛微信支付异步发往支付中心消息{}", message);
                logger.info("FinancialYsCallBackServiceImpl.weChatCallBack()---同步返回银盛微信支付异步接口通知应答", "success");
                printWriter.println("success");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    /**
     * 银盛支付宝支付异步回调地址
     *
     * @param params
     * @param response
     */
    @Override
    public void aliPayCallBack(Map<String, String> params, HttpServletResponse response) {
        PrintWriter printWriter = null;
        String ysPayAliPayJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsPayDTO = JsonUtils.parseObject(ysPayAliPayJson);
        logger.info("FinancialYsCallBackServiceImpl.aliPayCallBack()---请求到的银盛微信支付异步回执信息为：" + params);
        try {
            printWriter = response.getWriter();
            boolean flag = financialYsPayVerifyJsonSignService.verifySign(params, financialYsPayDTO);
            logger.info("银盛支付宝支付异步回执签名验证情况" + flag);
            if (flag == true) {
                String msg = JSON.toJSONString(params, SerializerFeature.DisableCircularReferenceDetect);
                Message message = new Message(FinancialYsPayReturnMQConfig.YS_TOPIC, FinancialYsPayReturnMQConfig.YS_SERVICE_ALIPAY_TAG, msg.getBytes());
                producer.send(message);
                logger.info("FinancialYsCallBackServiceImpl.aliPayCallBack()---银盛支付宝异步发往支付中心消息{}", message);
                logger.info("FinancialYsCallBackServiceImpl.aliPayCallBack()---同步返回银盛支付宝支付异步接口通知应答", "success");
                printWriter.println("success");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    /**
     * 银盛分账异步回调地址
     *
     * @param params
     * @param response
     */
    @Override
    public void splitCallBack(Map<String, String> params, HttpServletResponse response) {
        PrintWriter out = null;
        String ysPayAliPayJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsPayDTO = JsonUtils.parseObject(ysPayAliPayJson);
        logger.info("FinancialYsCallBackServiceImpl.splitCallBack()---请求到的银盛分账异步回执信息为：" + JsonUtils.toJSon(params));
        try {
            Message message = null;
            boolean verifyResult = financialYsPayVerifyJsonSignService.verifySign(params, financialYsPayDTO);
            out = response.getWriter();
            // 状态
            if (verifyResult) {// 验证成功
                logger.info("FinancialYsCallBackServiceImpl.splitCallBack()---发送异步信息为：" + JsonUtils.objectToJson(params).getBytes());
                message = new Message(FinancialYsPayReturnMQConfig.YS_TOPIC, FinancialYsPayReturnMQConfig.YS_SERVICE_SPLIT_TAG, JsonUtils.objectToJson(params).getBytes());
                producer.send(message);
                logger.info("FinancialYsCallBackServiceImpl.splitCallBack()---异步分账回执通知成功信息" + new String(message.getBody()));
                logger.info("FinancialYsCallBackServiceImpl.splitCallBack()---同步返回银盛分账异步接口通知应答", "success");
                out.println("success");
            } else {// 验证失败
                logger.info("FinancialYsCallBackServiceImpl.splitCallBack()---异步通知验证签名失败" + new String(message.getBody()));
                out.println("fail");
            }
        } catch (Exception e) {
            logger.error("FinancialYsCallBackServiceImpl.splitCallBack()---银盛异步分账回执接口", e.getMessage());
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 银盛提现异步回调地址
     *
     * @param params
     * @param response
     */
    @Override
    public void withdrawalCallBack(Map<String, String> params, HttpServletResponse response) {
        PrintWriter out = null;
        String ysPayWithdrawalJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsPayDTO = JsonUtils.parseObject(ysPayWithdrawalJson);
        logger.info("FinancialYsCallBackServiceImpl.withdrawalCallBack()---请求到的银盛提现异步回执信息为：" + JsonUtils.toJSon(params));
        try {
            Message message = null;
            boolean verifyResult = financialYsPayVerifyJsonSignService.verifySign(params, financialYsPayDTO);
            out = response.getWriter();
            // 状态
            if (verifyResult) {// 验证成功
                message = new Message(FinancialYsPayReturnMQConfig.YS_TOPIC, FinancialYsPayReturnMQConfig.YS_SERVICE_WITHDRAWAL_TAG, JsonUtils.objectToJson(params).getBytes());
                producer.send(message);
                logger.info("FinancialYsCallBackServiceImpl.withdrawalCallBack()---异步提现回执通知成功信息" + new String(message.getBody()));
                logger.info("FinancialYsCallBackServiceImpl.withdrawalCallBack()---同步返回银盛提现异步接口通知应答", "success");
                out.println("success");
            } else {// 验证失败
                logger.info("FinancialYsCallBackServiceImpl.withdrawalCallBack()---异步提现通知验证签名失败" + new String(message.getBody()));
                out.println("fail");
            }
        } catch (Exception e) {
            logger.error("FinancialYsCallBackServiceImpl.withdrawalCallBack()---银盛异步提现回执接口", e.getMessage());
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 银盛代付异步回调地址
     *
     * @param request
     * @param response
     */
    @Override
    public void paymentCallBack(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = ParamUtils.getParamMap(request);
        PrintWriter out = null;
        String ysPaymentJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsPayDTO = JsonUtils.parseObject(ysPaymentJson);
        logger.info("FinancialYsCallBackServiceImpl.paymentCallBack()---请求到的银盛代付异步回执信息为：" + JsonUtils.toJSon(params));
        try {
            Message message = null;
            boolean verifyResult = financialYsPayVerifyJsonSignService.verifySign(params, financialYsPayDTO);
            out = response.getWriter();
            // 状态
            if (verifyResult) {// 验证成功
                message = new Message(FinancialYsPayReturnMQConfig.YS_TOPIC, FinancialYsPayReturnMQConfig.YS_SERVICE_PAYMENT_TAG, JsonUtils.objectToJson(params).getBytes());
                producer.send(message);
                logger.info("FinancialYsCallBackServiceImpl.paymentCallBack()---异步提现回执通知成功信息" + new String(message.getBody()));
                logger.info("FinancialYsCallBackServiceImpl.paymentCallBack()---同步返回银盛代付异步接口通知应答", "success");
                out.println("success");
            } else {// 验证失败
                logger.info("FinancialYsCallBackServiceImpl.paymentCallBack()---异步提现通知验证签名失败" + new String(message.getBody()));
                out.println("fail");
            }
        } catch (Exception e) {
            logger.error("FinancialYsCallBackServiceImpl.paymentCallBack()---银盛异步代付回执接口", e.getMessage());
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
